﻿using Com.Aote.ObjectTools;
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Json;
using System.Collections.Generic;
using Com.Aote.Behaviors;
using Com.Aote.Behaviors;
using Com.Aote.Utils;
using Com.Aote.Controls;


namespace Com.Aote.Pages
{
    public partial class 机表预存 : UserControl
    {
        public 机表预存()
        {
            // Required to initialize variables
            InitializeComponent();
        }

        #region SaveClick 提交按钮操作过程
        // 提交数据到后台服务器
        private void SaveClick(object sender, RoutedEventArgs e)
        {
            //如果数据有错，提示不能保存
            GeneralObject kbfee = kbfee1.DataContext as GeneralObject;
            if (kbfee.HasErrors)
            {
                MessageBox.Show("输入数据有错，请检查！");
                return;
            }
            GeneralObject loginUser = (GeneralObject)FrameworkElementExtension.FindResource(this, "LoginUser");
            if (loginUser == null)
            {
                MessageBox.Show("无法获取当前登陆用户信息,请重新登陆后操作!");
                return;
            }
            //查询收据号
            GeneralObject LoginUsershouju = (GeneralObject)(from r in loader.Res where r.Name.Equals("LoginUsershouju") select r).First();
            LoginUsershouju.DataLoaded += LoginUserfapiao_DataLoaded;
            LoginUsershouju.Load();
            
        }

        void LoginUserfapiao_DataLoaded(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            GeneralObject LoginUsershouju = sender as GeneralObject;
            LoginUsershouju.DataLoaded -= LoginUserfapiao_DataLoaded;
            //if (e.Error != null)
            //{
            //    MessageBox.Show("没有分配收据号，不能预存！");
            //    return;
            //}
            //string fapiaohao = LoginUsershouju.GetPropertyValue("fapiaohao") + "";
            //if (string.IsNullOrEmpty(fapiaohao))
            //{
            //    MessageBox.Show("没有分配收据号，不能预存！");
            //    return;
            //}
            GeneralObject loginUser = (GeneralObject)FrameworkElementExtension.FindResource(this, "LoginUser");
            string loginid = (string)loginUser.GetPropertyValue("id");
            string orgpathstr = (string)loginUser.GetPropertyValue("orgpathstr");
            //显示正在工作
            busy.IsBusy = true;
            string handids = "0";
            //发票号
            GeneralObject kbfee = kbfee1.DataContext as GeneralObject;
            string f_invoicenum = kbfee.GetPropertyValue("f_invoicenum") + "";
            if (string.IsNullOrEmpty(f_invoicenum))
            {
                f_invoicenum = "0";
            }
            //获取基础地址
            WebClientInfo wci = (WebClientInfo)Application.Current.Resources["server"];

            // 提交
            string str = wci.BaseAddress + "/sell/" + ui_userid.Text + "/" + shoukuan.Text + "/"
                + ui_zhinajin.Text + "/" + f_payment.SelectedValue + "/" + loginid + "/" + orgpathstr + "/" + handids + "/" + f_invoicenum + "?uuid=" + System.Guid.NewGuid().ToString();

            Uri uri = new Uri(str);
            WebClient client = new WebClient();
            client.DownloadStringCompleted += client_DownloadStringCompleted;
            client.DownloadStringAsync(uri);
        }
 

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            busy.IsBusy = false;
            // 没有出错
            if (e.Error == null)
            {
                //把数据转换成JSON
                JsonObject item = JsonValue.Parse(e.Result) as JsonObject;
                if (item.ContainsKey("error"))
                {
                    string error = item["error"];
                    MessageBox.Show("交费失败：" + error);
                    return;
                }
                //把收费id放到收费对象
                GeneralObject retsell = (GeneralObject)(from r in loader.Res where r.Name.Equals("retsell") select r).First();
                retsell.FromJson(item);
                //把交费返回的对象放到打印对象中
                GeneralObject printobj = aofengprint.DataContext as GeneralObject;
                printobj.FromJson(item);
                //弹出是否打印
                print.TipCompleted -= print_TipCompleted;
                print.TipCompleted += print_TipCompleted;
                print.TipNoPrint();
            }
            else
            {
                // 提示出错
                MessageBox.Show("交易失败，链接错误！如果继续失败，请联系系统管理员。");
                // 清除界面数据
                Clear();
            }

            //清楚查询条件数据，焦点到用户编号条件。
            usernameSearch.Text = string.Empty;
            addressSearch.Text = string.Empty;
            phoneSearch.Text = string.Empty;
            useridSearch.Text = string.Empty;
            useridSearch.Focus();

            Decimal totalBot = decimal.Parse(totalBottom.Text);//界面上的合计
            Decimal sk = decimal.Parse(shoukuan.Text);//收款
            totalBot += sk;
            totalBottom.Text = totalBot.ToString("0.##");
        }

        void print_TipCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            GeneralObject fpinfosobj = (GeneralObject)(from r in loader.Res where r.Name.Equals("fpinfosobj") select r).First();
            fpinfosobj.DataLoaded += fpinfosobj_DataLoaded;
            fpinfosobj.Load();
        }

        void fpinfosobj_DataLoaded(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            GeneralObject fpinfosobj = (GeneralObject)sender;
            fpinfosobj.DataLoaded -= fpinfosobj_DataLoaded;
            GeneralObject kbfee = kbfee1.DataContext as GeneralObject;
            string f_invoicenum = kbfee.GetPropertyValue("f_invoicenum") + "";
            MessageBox.Show("当前打印收据号：" + f_invoicenum);
            //更新收费记录收据号
            HQLAction updateshouju = (HQLAction)(from r in loader.Res where r.Name.Equals("updateshouju") select r).First();
            updateshouju.Invoke();
            //保存发票信息
            //fpinfosobj.SetPropertyValue("f_username", kbfee.GetPropertyValue("f_username"), true);
            SystemTime SysTime = (SystemTime)FrameworkElementExtension.FindResource(this, "SysTime");
            GeneralObject loginUser = (GeneralObject)FrameworkElementExtension.FindResource(this, "LoginUser");
            fpinfosobj.SetPropertyValue("f_shoujustatue", "已用", true);
            fpinfosobj.SetPropertyValue("f_shoujutype", "机表收费", true);
            fpinfosobj.SetPropertyValue("f_userid", kbfee.GetPropertyValue("f_userid"), true);
            fpinfosobj.SetPropertyValue("f_gas", kbfee.GetPropertyValue("f_pregas"), true);
            fpinfosobj.SetPropertyValue("f_money", kbfee.GetPropertyValue("f_preamount"), true);
            fpinfosobj.SetPropertyValue("f_repairfee", kbfee.GetPropertyValue("f_amountmaintenance"), true);
            fpinfosobj.SetPropertyValue("f_totalfee", kbfee.GetPropertyValue("f_totalcost"), true);
            fpinfosobj.SetPropertyValue("f_grossproceeds", kbfee.GetPropertyValue("f_grossproceeds"), true);
            fpinfosobj.SetPropertyValue("f_sgnetwork", loginUser.GetPropertyValue("f_parentname"), true);
            fpinfosobj.SetPropertyValue("f_orgstr", loginUser.GetPropertyValue("orgpathstr"), true);
            fpinfosobj.SetPropertyValue("f_sgoperator", loginUser.GetPropertyValue("name"), true);
            fpinfosobj.SetPropertyValue("f_filiale", loginUser.GetPropertyValue("f_fengongsi"), true);
            fpinfosobj.SetPropertyValue("f_fapiaotime", SysTime.Now, true);
            fpinfosobj.SetPropertyValue("f_fapiaodate", SysTime.Now, true);
            fpinfosobj.Save();
            print.UseDefaultPrinter = true;
            print.Print();
        }
        #endregion

        private void Compute()
        {
            // 取出余额
            decimal f_zhye = decimal.Parse(zhye.Text);
            // 拿余额+实缴金额算未交费抄表记录是否应该交费
            decimal money = decimal.Parse(shoukuan.Text);
            decimal zhinajin = decimal.Parse(ui_zhinajin.Text);
            decimal total = f_zhye + money - zhinajin;

            // 存放所有扣费的表号
            List<string> userids = new List<string>();

            // 总的上期指数
            decimal lastnum = 0m;
            // 总气量
            decimal gasSum = 0m;
            // 总气费
            decimal feeSum = 0m;

            
            // 当前正在处理的表号
            String currentId = "";
            // 当前表是否可以继续扣减
            bool canSub = true;


            //把计算结果放到界面上
            ui_lastinputgasnum.Text = lastnum.ToString("0.#");
            ui_lastrecord.Text = (lastnum + gasSum).ToString("0.#");
            ui_pregas.Text = gasSum.ToString("0.#");
            ui_preamount.Text = feeSum.ToString("0.##");
            //应交金额=气费-上期结余
            decimal f_totalcost = (feeSum - f_zhye + zhinajin) > 0 ? (feeSum - f_zhye + zhinajin) : 0;
            ui_totalcost.Text = f_totalcost.ToString("0.##");
            //本期结余=上期结余+实收-气费
            decimal f_benqizhye = f_zhye + money - feeSum - zhinajin;
            ui_benqizhye.Text = f_benqizhye.ToString("0.##");

        }

        // 清除界面上的数据
        private void Clear()
        {
            // 清除交费内容
            GeneralObject kbfee = (GeneralObject)(from r in loader.Res where r.Name.Equals("kbfee") select r).First();
           
            kbfee.New();
            // 当前选中用户为空
            userfiles.SelectedItem = null;
        }

         

        #region 选中新用户后的处理过程
        private void userfiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //取当前选中项的用户编号，传递到后台取数据
            GeneralObject go = userfiles.SelectedItem as GeneralObject;
            if (go == null)
            {
                return;
            }
            //kbsellgasbusy.IsBusy = true;
            busy.IsBusy = true;
            string f_userid = go.GetPropertyValue("f_userid").ToString();
            GeneralObject loginuser = (GeneralObject)FrameworkElementExtension.FindResource(this.save2, "LoginUser");
            string fengongsi = loginuser.GetPropertyValue("f_fengongsi").ToString();
            WebClientInfo wci = Application.Current.Resources["server"] as WebClientInfo;
            string uri = wci.BaseAddress + "/sell/bill/" + f_userid + "/" + fengongsi + "?uuid=" + System.Guid.NewGuid().ToString();
            WebClient client = new WebClient();
            client.DownloadStringCompleted += userfiles_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri(uri));
        }

        void userfiles_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
           // kbsellgasbusy.IsBusy = false;
            busy.IsBusy = false;

            if (e.Error != null)
            {
                MessageBox.Show("查询失败，链接错误！");
                Clear();
                return;
            }

            //把数据转换成JSON
            JsonObject item = JsonValue.Parse(e.Result) as JsonObject;
            if (item.ContainsKey("error"))
            {
                string error = item["error"];
                MessageBox.Show("查询失败：" + error);
                busy.IsBusy = false;
                return;
            }
            JsonArray bills = item["f_hands"] as JsonArray;
            //有欠费不能预存
            if (bills.Count > 0)
            {
                MessageBox.Show("该用户有" + bills.Count + "条欠费记录，不能预存，请先去交费！");
                Clear();
                return;
            }
            //把用户数据写到交费界面上
            ui_username.Text = (string)item["f_username"];
            ui_usertype.Text = (string)item["f_usertype"];
            ui_districtname.Text = (string)item["f_districtname"];
            ui_gasproperties.Text = (string)item["f_gasproperties"];
            ui_stairpricetype.Text = (string)item["f_stairtype"];
            zhye.Text = item["f_zhye"].ToString();
            ui_address.Text = (string)item["f_address"];
            //ui_gaspricetype.Text = (String)item["f_gaspricetype"];
            ui_userid.Text = (string)item["infoid"];
            zhe.Text = item["f_zherownum"].ToString();
            //ui_dibaohu.IsChecked = item["f_dibaohu"].ToString().Equals("1");
            ui_userstate.Text = (string)item["f_userstate"];
            ui_paytype.Text = (string)item["f_payment"];
            // 当前正在处理的表号
            String currentId = "";
            // 总的上期指数
            decimal lastnum = 0;
            // 总气量
            decimal gasSum = 0;
            // 总气费
            decimal feeSum = 0;
            //总的滞纳金
            decimal zhinajinAll = 0;
            //余额
            decimal f_zhye = decimal.Parse(item["f_zhye"].ToString());
            // 计算出来的总气量等放到用户界面上
            ui_pregas.Text = gasSum.ToString("0.#");//总气量
            ui_lastinputgasnum.Text = lastnum.ToString("0.#");//总上期底数
            ui_lastrecord.Text = (lastnum + gasSum).ToString("0.#");//总本期底数
            ui_zhinajin.Text = zhinajinAll.ToString("0.##");//总滞纳金
            ui_linshizhinajin.Text = zhinajinAll.ToString("0.##");//滞纳金
            ui_preamount.Text = feeSum.ToString("0.##");//气费金额
            decimal f_totalcost = feeSum - f_zhye + zhinajinAll > 0 ? feeSum - f_zhye + zhinajinAll : 0;
            ui_totalcost.Text = f_totalcost.ToString("0.##");//应缴金额
            decimal f_benqizhye = (decimal)(f_zhye - feeSum - zhinajinAll > 0 ? f_zhye - feeSum - zhinajinAll : 0);
            ui_benqizhye.Text = f_benqizhye.ToString("0.##");//本期结余
            shoukuan.Text = f_totalcost.ToString("0.##");

        }
        #endregion

        

        private void cancle_Click(object sender, RoutedEventArgs e)
        {
            Clear();

        }

        private void print_Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            GeneralObject kbfee = (GeneralObject)(from r in loader.Res where r.Name.Equals("kbfee") select r).First();
            //打印折子
            GeneralObject dz = (from p in loader.Res where p.Name.Equals("dazhe") select p).First() as GeneralObject;
            if (dz.GetPropertyValue("value").ToString() == "是")
            {
                PrintObj zzprint = FrameworkElementExtension.FindResource(this.save2, "zzprint") as PrintObj;
                zzprint.Completed += zzprint_Completed;
                zzprint.TipPrint();
            }
            else
            {
                kbfee.New();
                MessageBox.Show("交费完成！");
                Clear();
            }
            string f_invoicenum = kbfee.GetPropertyValue("f_invoicenum") + "";
            if (!string.IsNullOrEmpty(f_invoicenum))
            {
                int i = Int32.Parse(f_invoicenum) + 1;
                kbfee.SetPropertyValue("f_invoicenum", i + "", true);
            }
        }

        void zzprint_Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            PrintObj zzprint = sender as PrintObj;
            zzprint.Completed -= zzprint_Completed;
            //打印完成清空
            GeneralObject kbfee = (GeneralObject)(from r in loader.Res where r.Name.Equals("kbfee") select r).First();
            kbfee.New();
            MessageBox.Show("交费完成！");
            Clear();
        }

        private void totalBottom_click(object sender, RoutedEventArgs e)
        {
            totalBottom.Text = "0";
        }
    }
}
